<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->

<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <!--<div style="line-height: 50px;color: #606266;">-->
        <!--<span>来源：</span>-->
        <!--<el-radio-group v-model="listQuery.keyword" @change="sourceChange">-->
          <!--<el-radio label="1">app</el-radio>-->
          <!--<el-radio label="2">pc商城</el-radio>-->
        <!--</el-radio-group>-->
      <!--</div>-->
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="关键字" v-model="listQuery.username"></el-input>
      <div style="width: 400px!important;margin-left: 20px;" class="filter-item">
        <el-date-picker
          v-model="activityTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="活动开始时间"
          end-placeholder="活动结束时间">
        </el-date-picker>
      </div>
      <div style="width: 200px!important;margin-left: 20px;" class="filter-item">
        <el-select v-model="listQuery.activityType" placeholder="活动方式">
          <el-option
            v-for="item in activityList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div style="width: 150px!important;margin-left: 20px;" class="filter-item">
        <el-select v-model="listQuery.status" placeholder="状态">
          <el-option
            v-for="item in activityList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-button class="filter-item" style="margin-left: 20px;margin-right: 20px;" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button style="display: block;margin-left: 0px;" type="success" @click="handleAdd">新增活动<i class="el-icon-plus el-icon--right"></i></el-button>
      <!--<el-button style="display: block;margin-left: 0px;" type="success" v-waves icon="search" @click="handleFilter">新增</el-button>-->
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 99%">

      <el-table-column align="center" label="端口">
        <template slot-scope="scope">
          <span>{{scope.row.dateSource ? '商城' : '供应链'}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="活动商品信息" width="250">
        <template slot-scope="scope">
          <img style="width: 50px;height: 50px;display: inline-block;vertical-align: top;" :src="scope.row.goodsImg" alt="">
          <span style="vertical-align: top;display: inline-block;line-height: 50px;">{{scope.row.goodsName}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="原价">
        <template slot-scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="活动价">
        <template slot-scope="scope">
          <span>{{scope.row.discountPrice}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="活动方式">
        <template slot-scope="scope">
          <span>{{scope.row.activityType | typeFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column width="160" align="center" label="活动开始时间">
        <template slot-scope="scope">
          <span>{{scope.row.activityStartTime}}</span>
        </template>
      </el-table-column>

      <el-table-column width="160" align="center" label="活动结束时间">
        <template slot-scope="scope">
          <span>{{scope.row.activityEndTime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="status-col" label="状态">
        <template slot-scope="scope">
          <el-tag>{{scope.row.status === '1' ? '开始' : '结束'}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleCheckDetail(scope.row)">查看</el-button>
          <!--<el-button size="small" type="success" @click="handleCheckDetail(scope.row)">启用</el-button>-->
          <!--<el-button size="small" type="info" @click="handleCheckDetail(scope.row)">停止</el-button>-->
          <el-button size="small" type="danger" @click="deletes(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!--弹窗-->
    <el-dialog title="新增活动" :visible.sync="dialogShow">
      <el-form :model="form" ref="form" label-width="100px">

        <el-form-item label="商品来源" prop="dataSource">
          <el-select class="select-width" v-model="form.dataSource" placeholder="商品来源">
            <el-option
              v-for="item in sourceList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动方式" prop="activityType">
          <el-select class="select-width" v-model="form.activityType" placeholder="活动方式">
            <el-option
              v-for="item in activityList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动商品" prop="goods">
          <el-autocomplete
            v-model="selectGoods"
            :fetch-suggestions="querySearchAsync"
            hide-loading="true"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
          <el-table v-if="goodsList.length > 0" :data="goodsList" border style="margin-top: 20px;">
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="salePrice" label="价格"></el-table-column>
            <el-table-column prop="address" label="折扣价">
              <template slot-scope="scope">
                <el-input v-model="scope.row.discountPrice" placeholder="请输入折扣价"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="活动起止时间" prop="activityTime">
          <div style="width: 400px!important;" class="filter-item">
            <el-date-picker
              v-model="form.activityTime"
              type="datetimerange"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="活动开始时间"
              end-placeholder="活动结束时间">
            </el-date-picker>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button type="primary" @click="update('form')">确 定</el-button>
        <!--<el-button v-else type="primary" @click="update('form')">修 改</el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getActivityList, queryGoodsList, queryDictList, addActivity, deleteActivity } from '@/api/goods'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  import { mapGetters } from 'vuex'

  export default {
    name: 'seller_index',
    directives: {
      waves
    },
    data() {
      return {
        activityList: [],
        sourceList: [
          {
            value: '1',
            label: 'app'
          },
          {
            value: '2',
            label: 'pc商城'
          }
        ], // 商品来源
        selectGoods: '', //
        goodsList: [], // 选中商品列表
        dialogShow: false,
        loading: false,
        list: null, // 列表数据
        total: null, // 总条数
        listLoading: true, // loading
        listQuery: { // 请求参数
          pageNo: 1,
          pageSize: 10,
          keyword: ''
        },
        activityTime: '',
        form: {},
        tableKey: 0
      }
    },
    computed: {
      ...mapGetters(['permissions'])
    },
    filters: {
      typeFilter(type) {
        const typeMap = {
          1: '优质精选',
          2: '特价爆棚',
          3: '最新',
          4: '畅销'
        }
        return typeMap[Number(type)]
      }
    },
    created() {
      this.getList()
      this.queryActivityList()
      // this.sys_user_add = this.permissions['sys_user_add']
      // this.sys_user_upd = this.permissions['sys_user_upd']
      // this.sys_user_del = this.permissions['sys_user_del']
    },
    methods: {
      sourceChange(val) { // 来源切换
        this.listQuery.pageNo = 1
        this.getList()
      },
      filterJavaTime(str) {
        const times = new Date(str).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
        // const times = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
        return times.substring(0, 11)
      },
      typeFilter(type) { // type过滤
        let str = ''
        this.activityList.forEach(item => {
          if (type === item.value) {
            str = item.description
          }
        })
        console.log(str)
        return str
      },
      handleAdd() { // 添加活动
        this.dialogShow = true
      },
      queryActivityList() { // 查询活动类型
        const that = this
        queryDictList('goods_activity').then(res => {
          res.data.data.forEach(item => {
            const obj = {
              value: item.value,
              label: item.description
            }
            that.activityList.push(obj)
          })
        })
      },
      querySearchAsync(queryString, cb) {
        const that = this
        if (!that.form.dataSource) {
          that.$message.error('请选择商品来源')
          return
        }
        const params = {
          pageNo: 1,
          pageSize: 10,
          source: that.form.dataSource,
          keyword: queryString
        }
        queryGoodsList('/app/operateGoods/page', params).then(res => {
          const list = res.data.data.records
          list.forEach(item => {
            item.value = item.productName
          })
          cb(list)
        })
      },
      handleSelect(item) {
        this.goodsList.push(item)
      },
      getList() {
        // const that = this
        this.listLoading = true;
        getActivityList(this.listQuery).then(response => {
          this.list = response.data.data.records
          this.total = response.data.data.total
          this.listLoading = false
        });
      },
      handleChangeType() { // 切换类型
        this.listQuery.pageNo = 1
        this.getList()
      },
      handleFilter() { // 搜索
        this.listQuery.pageNo = 1
        this.getList()
      },
      handleSizeChange(val) { // 页面大小切换
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) { // 页码切换
        this.listQuery.pageNo = val
        this.getList()
      },
      handleCheckDetail(row) { // 查看详情
        this.dialogShow = true
      },
      cancel(formName) { // 取消
        this.dialogShow = false
        this.$refs[formName].resetFields()
      },
      update() {
        const that = this
        const param = []
        that.goodsList.forEach(item => {
          const obj = {
            goodsId: item.id,
            dataSource: that.form.dataSource,
            goodsName: item.productName,
            goodsImg: item.surfaceImgUrl,
            price: item.prePrice,
            discountPrice: item.discountPrice,
            activityType: that.form.activityType,
            startTime: that.form.activityTime[0],
            endTime: that.form.activityTime[1]
          }
          param.push(obj)
        })
        console.log(param)
        addActivity(param).then(response => {
          this.$message.success('提交成功')
          this.dialogShow = false
          this.getList()
        })
      },
      deletes(row) {
        this.$confirm(
          '此操作将永久删除, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          deleteActivity(row.id).then(res => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
      }
    }
  }
</script>

<style scoped>
  .line-word {
    padding: 0 15px;
  }
  .image {
    display: inline-block;
    width: 150px;
    margin-right: 30px;
  }
  .select-width {
    width: 150px!important;
  }
</style>
